<template>
  <view>
    <view>
      <input type="number" v-model="num1" placeholder="请输入第一个数字" @input="calculate"/>
      <input type="number" v-model="num2" placeholder="请输入第二个数字" @input="calculate"/>
    </view>
  </view>
</template>

<script>
export default {
  name: 'CalculatorComponent',
  props: {
    operation: {
      type: String,
      required: true,
      validator: function(value) {
        return ['add', 'subtract', 'multiply', 'divide'].includes(value)
      }
    },
    initialNum1: {
      type: Number,
    },
    initialNum2: {
      type: Number,
    }
  },
  data() {
    return {
      num1: this.initialNum1,
      num2: this.initialNum2,
      result: null,
      error: ''
    }
  },
  watch: {
    initialNum1(newVal) {
      this.num1 = newVal
    },
    initialNum2(newVal) {
      this.num2 = newVal
    }
  },
  methods: {
    calculate() {
      this.error = ''
      const n1 = Number(this.num1)
      const n2 = Number(this.num2)
      switch(this.operation) {
        case 'add':
          this.result = n1 + n2
          break
        case 'subtract':
          this.result = n1 - n2
          break
        case 'multiply':
          this.result = n1 * n2
          break
        case 'divide':
          if (n2 === 0) {
            this.error = '除数不能为0'
            this.result = null
          } else {
            this.result = n1 / n2
          }
          break
      }
      this.$emit('result', {
        result: this.result,
        error: this.error,
        num1: n1,
        num2: n2
      })
    }
  },
  mounted() {
    this.calculate()
  }
}
</script>
<style>
	input {
		margin: 10px;
		flex: 1;
		padding: 20rpx;
		border: 1px solid #ddd;
		border-radius: 8rpx;
}
</style>
